//
//  YSMineCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/6/28.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSMineCtrl.h"
#import "YSAddressCtrl.h"
#import "YSOrderViewCtrl.h"
#import "CustomNavigationCtrl.h"
#import "YSMineDataTool.h"
#import "YSModifyInfoCtrl.h"
#import "YSVoucherCtrl.h"
#import "YSFeedbackCtrl.h"
#import "YSAboutCtrl.h"
#import "YSMarkCtrl.h"
#import "YSMineCell.h"
#import "YSMineItemModel.h"
#import "YSMineHeaderView2.h"
#import "YSCustomerServiceCtrl.h"


@interface YSMineCtrl ()<UIAlertViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) YSMineHeaderView2 *headerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *itemArray;
@property (strong, nonatomic) UIImageView *bgHeadView;

@end

@implementation YSMineCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    [self initItem];
    [self initView];
    [self requestData];
    [self registNortif];
 
    //添加一个背景头
    self.bgHeadView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_loding_defalut"]];
    [self.bgHeadView setX:0];
    [self.bgHeadView setY:-NavWithStatusBarH];
    [self.bgHeadView setWidth:SCREENW];
    [self.view insertSubview:self.bgHeadView belowSubview:self.tableView];
    
}

-(void)registNortif{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(repeatUpdateInfo:) name:kUpdateMineInfoNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealNewMessageBadge) name:kDealNewMessageBadgeNortif object:nil];
}

-(BOOL)shouldStatusBarLightContent{
    return YES;
}

-(void)initView{
    //header view
    YSMineHeaderView2 *headerView  = [YSMineHeaderView2 headerView];
    [headerView setWidth:SCREENW];
    self.headerView = headerView;
    
    
    //tableview
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setTableHeaderView:self.headerView];
    [self.tableView setTableFooterView:[UIView new]];
    [self.tableView registerNib:[UINib nibWithNibName:@"YSMineCell" bundle:nil]
         forCellReuseIdentifier:@"YSMineCell"];
    [self.tableView setSeparatorColor:HEXColor(@"#e5e5e5")];
    
     NSLog(@"headerView:-------%@",NSStringFromCGRect(self.headerView.frame));
}

-(void)initItem{
    _itemArray = [NSMutableArray array];
    
    YSMineItemModel *addressItem = [[YSMineItemModel alloc]initWithItemName:@"收货地址" iconName:@"icon_mine_location" targetClass:[YSAddressCtrl class] hasNew:NO];
    [addressItem setOperation:^{
       [self.navigationController pushViewController:[[YSAddressCtrl alloc]initWithType:MineType] animated:YES];
    }];
    YSMineItemModel *aboutItem = [[YSMineItemModel alloc]initWithItemName:@"关于悦食" iconName:@"icon_mine_about" hasNew:NO];
    [aboutItem setOperation:^{
        [self.navigationController pushViewController:[YSAboutCtrl new] animated:YES];
    }];
    YSMineItemModel *customerServiceItem = [[YSMineItemModel alloc] initWithItemName:@"联系客服" iconName:@"customer_service" hasNew:NO];
    [customerServiceItem setOperation:^{
       [self.navigationController pushViewController:[YSCustomerServiceCtrl new] animated:YES];
    }];
    YSMineItemModel *reviewItem = [[YSMineItemModel alloc]initWithItemName:@"给个好评" iconName:@"icon_mine_review" hasNew:NO];
    [reviewItem setOperation:^{
        NSString *url = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=";
        url = [url stringByAppendingString:kAppleId];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }];
    YSMineItemModel *clearItem = [[YSMineItemModel alloc]initWithItemName:@"清除缓存" iconName:@"icon_mine_clear" hasNew:NO];
    [clearItem setOperation:^{
        [[SDImageCache sharedImageCache] clearDisk];
        ShowTips(@"清除成功");
    }];
    YSMineItemModel *feedbackItem = [[YSMineItemModel alloc]initWithItemName:@"意见反馈" iconName:@"icon_mine_feedback" targetClass:[YSFeedbackCtrl class] hasNew:NO];
    [feedbackItem setOperation:^{
        [self.navigationController pushViewController:[YSFeedbackCtrl new] animated:YES];
    }];
    YSMineItemModel *exitItem = [[YSMineItemModel alloc]initWithItemName:@"退出登录" iconName:@"btn_mine_exit" hasNew:NO];
    [exitItem setOperation:^{
        UIAlertView *alert =  [[UIAlertView alloc]initWithTitle:@"确定退出吗?" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }];
    [_itemArray addObjectsFromArray:@[addressItem,aboutItem,customerServiceItem, reviewItem,clearItem,feedbackItem,exitItem]];
}

-(void)repeatUpdateInfo:(NSNotification *)nortif{
    [self initItem];
    [self requestData];
    [self.tableView reloadData];
}

-(void)dealNewMessageBadge{
    if (ISLOGIN){
        YSMineItemModel *chatModel =  _itemArray[2];
        chatModel.hasNew = [DefaultsHelper boolForKey:kHasNewChatMessage];;
        [self.tableView reloadData];
    }
}

-(void)dealHeadView{
    NSString *headUrl =  [DefaultsHelper stringForKey:kHeadImg];
    if(ISBLANK(headUrl)){
        [self.headerView.loginBtn setBackgroundImage:[UIImage imageNamed:@"bg_login_defalut"] forState:UIControlStateNormal];
    }else{
        [self.headerView.loginBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:headUrl] forState:UIControlStateNormal];
    }
    
    NSString *name = [DefaultsHelper stringForKey:kNickName];
    [self.headerView.nameLabel setText:name];
    [self.headerView.loginBtn setTitle:@"" forState:UIControlStateNormal];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(ISLOGIN){
        [self dealHeadView];
        [self dealNewMessageBadge];
    }else{
      [self.headerView.nameLabel setText:@""];
      [self.headerView.loginBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
      [self.headerView.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
      if(self.itemArray.count>5){
          [self.itemArray removeLastObject];
          [self.tableView reloadData];
      }
    }
}

-(void)requestData{
    if (ISLOGIN) {
        [YSMineDataTool getMineInfo:0 success:^(YSRegisterRes *result) {
            if(result.isSucc){
                [result saveUserInfo];
                [self dealHeadView];
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YSMineCell *cell = [YSMineCell cellWithTableView:tableView];
    cell.itemModel =  self.itemArray[indexPath.row];
    cell.separatorInset = UIEdgeInsetsMake(0, YSPublicXInset*3+5, 0, 0);
    return cell;
}

#pragma mark - Table view 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YSMineItemModel *itemModel = self.itemArray[indexPath.row];
    if(itemModel.operation){
        itemModel.operation();
    }
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [Utils clearExitInfo];
        [self.headerView.loginBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.headerView.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [self.headerView.nameLabel setText:@""];
        [self.itemArray removeLastObject];
        [self.tableView reloadData];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kUpdateMineInfoNortif object:nil];
}

@end
